package com.example.test_witns.ui.my_qrcode;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.test_witns.ui.add_friends.AddFriendsActivity;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

public class ScanActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        // 启动扫描器
        new IntentIntegrator(this)
            .setPrompt("Scan a QR Code")
            .setOrientationLocked(false)
            .initiateScan();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result != null) {
            if (result.getContents() != null) {
                parseQrContent(result.getContents());
            } else {
                finish();
                Toast.makeText(this, "扫描取消", Toast.LENGTH_SHORT).show();
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    private void parseQrContent(String content) {
        String[] infos = content.split(",");
        Intent intent = new Intent(this, AddFriendsActivity.class);
        intent.putExtra("nickname", infos[0]);
        intent.putExtra("userId", infos[1]);
        intent.putExtra("uuid", infos[2]);
        intent.putExtra("userAvatarURL", infos[3]);
        startActivity(intent);
    }
}